package org.teststack.Test123;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class JmMD5 {public class MD5Example {
    public String toHexString(byte[] hash) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if(hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public String getMD5Hash(String input) {
        try {
            // 创建MD5 Hash
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算字符串的MD5散列值
            md.update(input.getBytes());
            byte[] digest = md.digest();
            // 将散列值转换为十六进制字符串
            return toHexString(digest);
        }
        // 指定算法的 MessageDigest 实例不存在时抛出异常
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public void main(String[] args) {
        String originalString = "Hello World!";
        String md5Result = getMD5Hash(originalString);
        System.out.println("The MD5 hash of '" + originalString + "' is: " + md5Result);
    }
}

}
